package com.shaobufan.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shaobufan.museum.mapper.UserVerificationMapper;
import com.shaobufan.museum.pojo.entity.UserVerification;
import com.shaobufan.museum.service.EmailService;
import com.shaobufan.museum.service.UserVerificationService;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Random;

import static com.shaobufan.museum.contant.EmailContent.*;

/**
 * @author 17126
 * &#064;description  针对表【user_verification(用户验证码)】的数据库操作Service实现
 * &#064;createDate  2024-04-01 10:48:12
 */
@Service
public class UserVerificationServiceImpl extends ServiceImpl<UserVerificationMapper, UserVerification>
        implements UserVerificationService {

    @Resource
    private EmailService emailService;

    @Resource
    private UserVerificationMapper userVerificationMapper;

    @Resource
    TemplateEngine templateEngine;

    /**
     * 发送验证码
     *
     * @param email 用户邮箱
     * @return 操作码
     */
    @Override
    public Integer sendVerificationCode(String email,String uuid) {
        Random random = new Random();
        Integer captcha = random.nextInt(8848) + 1000;

        //创建邮件正文
        Context context = new Context();
        context.setVariable("verifyCode", Arrays.asList(captcha.toString().split("")));
        String emailContent = templateEngine.process("/email-code", context);

        UserVerification userVerification = new UserVerification();
        userVerification.setTempKey(uuid);
        userVerification.setVerificationCode(captcha);

        userVerificationMapper.insert(userVerification);

        try {
            return emailService.sendTemplateEmail(email, EMAIL_VERIFY_TITLE, emailContent);
        } catch (MessagingException e) {
            return EMAIL_FAIL;
        }
    }

    /**
     * 验证邮箱验证码
     *
     * @param uuid   临时生成凭证
     * @param captcha 验证码
     * @return 操作状态码
     */
    @Override
    public Integer checkVerificationCode(String uuid, Integer captcha) {
        QueryWrapper<UserVerification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("temp_key", uuid);
        queryWrapper.select().orderByDesc("create_time").last("limit 1");
        UserVerification userVerification = userVerificationMapper.selectOne(queryWrapper);

        LocalDateTime dateTime = LocalDateTime.now();
        Duration duration = Duration.between(userVerification.getCreateTime(), dateTime);

        if (userVerification.getVerificationCode().equals(captcha) && duration.toMinutes() <= 5) {
            return EMAIL_CHECK_SUCCESS;
        }
        return EMAIL_CHECK_FAIL;
    }
}